//
//  ViewController.swift
//  ARKitDemo
//
//  Created by 李旭峰 on 2022/11/30.
//

import UIKit
import ARKit

class ViewController: UIViewController {
    @IBOutlet weak var sceneView: ARSCNView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        addBox()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap(withGesture:)))
        self.view.addGestureRecognizer(tapGesture)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let config = ARWorldTrackingConfiguration()
        sceneView.session.run(config, options: .resetTracking)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        sceneView.session.pause()
    }
    
    @objc func didTap(withGesture recognizer: UIGestureRecognizer) {
        let tapLocation = recognizer.location(in: sceneView)
        let hitTestResults = sceneView.hitTest(tapLocation, options: nil)
        guard let node = hitTestResults.first?.node else {
            let hitTestResultsWithFeaturePoints = sceneView.hitTest(tapLocation, types: .featurePoint)
            if let hitTestResultWithFeaturePoints = hitTestResultsWithFeaturePoints.first {
                let transtion = hitTestResultWithFeaturePoints.worldTransform.translation3v
                addBox(x: transtion.x, y: transtion.y, z: transtion.z)
            }
            return
        }
        node.removeFromParentNode()
    }
    
    func addBox(x:Float = 0, y: Float = 0, z: Float = 0) {
        let box = SCNBox(width: 0.1, height: 0.15, length: 0.1, chamferRadius: 0)
        let node = SCNNode()
        node.geometry = box
        node.position = SCNVector3(x, y, z)
        
//        let scene = SCNScene()
//        scene.rootNode.addChildNode(node)
//
//        sceneView.scene = scene
        
        sceneView.scene.rootNode.addChildNode(node)
    }
}

extension float4x4 {
    var translation3v:float3 {
        let translation = self.columns.3
        return float3(translation.x, translation.y, translation.z)
    }
}
